<?php
class Sales_model extends CI_Model {
    
    var $id = '';
    var $document_type_id = '';
    var $document_code = '';
    var $date = '';
    var $id_client = '';
    var $observations = '';
    private $_tabla = 'sales';
    
    public function add_sales($data){
		$this->db->insert($this->_tabla, $data);
	   	return $this->db->insert_id();
    }
    
    public function search($code = null)
    {
        $query = $this->db;
        if (isset($code) && $code != '') {
            $query = $query->like($this->_tabla.'.document_code', $code, 'both');
        }
       
        $query = $query->get($this->_tabla);
        $rs = $query->result();
        return $rs;
    }

    public function update_sale($id, $data)
	{
		$this->db->where('id_sale', $id);
		$this->db->update($this->_tabla, $data);
		return true;
	}


    public function edit_amout($document_code,$amount){
         return $this->db->query("UPDATE sales SET amount='".$amount."' WHERE `document_code`='".$document_code."'");
    }
    
    public function edit_stock_warehouse_product($code_product,$code_warehouse,$caja,$paquete,$unidad){
        $this->db->query("UPDATE  `warehouses_product` SET  `Units`=".$unidad.", `packs`=".$paquete.", `boxes`=".$caja." WHERE  `id_warehouse` =".$code_warehouse." and id_product = '".$code_product."'");
    }
    
    public function comparaction_code($document_code){
        $query = $this->db->query("SELECT document_code FROM sales where document_code = '".$document_code."'");
        $rs = $query->num_rows();
        return $rs;
    }
    
    public function select_almacen_productos($code_product, $code_almacen){
       $query = $this->db->query("SELECT * FROM  `warehouses_product` WHERE  `id_product` =  '".$code_product."' AND  `id_warehouse` = '".$code_almacen."'");
       $rs = $query->result();
       return $rs;
    }
    
    public function findDetails($sale_id){
		$query = $this->db->query("SELECT p.products_id, p.code, p.description, sd.box, sd.pack, sd.unit, sd.amount FROM products as p, sales_details as sd where p.products_id = sd.product_id and sd.sale_id = '".$sale_id."'");
        $rs = $query->result();
        return $rs;   
	}
    
    public function deleteAllDetails($sale_id){
		$this->db->query("DELETE FROM sales_details WHERE sale_id='".$sale_id."'");
	}
	
		public function findById($sale_id){
	    $this->db->select();
        $this->db->where('id_sale', $sale_id);
        $query = $this->db->get($this->_tabla);
        $rs = $query->result();
        
		if(count($rs)>0)
		    return $rs[0];
		else
			return false;
	}
}